package com.dcits.exception;

import com.dcits.common.Result;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

@Controller
public class CustomErrorControllerHandler implements ErrorController {

    @RequestMapping("/error")
    public ResponseEntity<Result> handleError(HttpServletRequest request) {
        final HttpStatus status = getStatus(request);
        return new ResponseEntity<>(Result.fail(status.value() + "000", "请求的资源不存在"), status);
    }

    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        return HttpStatus.valueOf(statusCode);
    }
}